package com.zsw.controller;

import com.zsw.util.R;
import com.zsw.util.RedisUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class IndexController {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisUtils redisUtils;

    @GetMapping("/sendMessage/{id}")
    public R getString(@PathVariable int id, @RequestParam(value = "name")String name){
        Map map=new ConcurrentHashMap();
        if(id!=0) {
            String value=redisUtils.get("ticketStatus");
            if(value!=null) {
                int count = Integer.valueOf(value);
                if (count == 0) {
                    map.put("user", name);
                    map.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    map.put("productId", id);
                    rabbitTemplate.convertAndSend("ticketExchange", "ticket", map);
                } else {
                    return R.ok("库存不足，抢票失败！");
                }
            }else {
                redisUtils.set("ticketStatus", String.valueOf(0), 1200);
            }
        }else {
            return R.error();
        }
        return R.ok();
    }
}
